#ifndef A8_SOCKETPOLL_HPP
#define A8_SOCKETPOLL_HPP

namespace a8
{
	class ClientSocketPool
	{
		struct ClientSocketNode
		{
			ClientSocketItem* clientsocket;
			time_t addtime;
			ClientSocketNode* next;
		};
	public:

		ClientSocketPool():mTopNode(NULL),
						   mBotNode(NULL),
						   mCount(0)
		{
		}

		~ClientSocketPool()
		{
			ClientSocketNode *pdelnode = mTopNode;
			while(mTopNode){
				pdelnode = mTopNode;
				mTopNode = mTopNode->next;
				delete pdelnode->clientsocket;
				free(pdelnode);
			}
		}

		void Add(ClientSocketItem* clientsocket)
		{
			ClientSocketNode *p = (ClientSocketNode*)malloc(sizeof(ClientSocketNode));
			memset(p, 0, sizeof(ClientSocketNode));
			p->clientsocket = clientsocket;
			p->addtime = time(NULL);
			if(mBotNode){
				mBotNode->next = p;
				mBotNode = p;
			}else{
				mTopNode = p;
				mBotNode = p;
			}
			mCount++;
		}

		ClientSocketItem* Get()
		{
			ClientSocketItem* p = NULL;
			if(mTopNode){
				if(time(NULL) - mTopNode->addtime >= 30){
					p = mTopNode->clientsocket;
					ClientSocketNode* pdelnode = mTopNode;
					mTopNode = mTopNode->next;
					if(!mTopNode){
						mBotNode = NULL;
					}
					free(pdelnode);
					mCount--;
				}
			}
			return p;
		}

		void ClearTimeOutSocket()
		{
			while(mTopNode){
				if(time(NULL) - mTopNode->addtime > 60 * 5){
					ClientSocketNode* pdelnode = mTopNode;
					mTopNode = mTopNode->next;
					if(!mTopNode){
						mBotNode = NULL;
					}
					delete pdelnode->clientsocket;
					free(pdelnode);
					mCount--;
				}else{
					break;
				}
			}
		}

		int Count()
		{
			return mCount;
		}

	private:
		ClientSocketNode* mTopNode;
		ClientSocketNode* mBotNode;
		int mCount;
	}; 
}

#endif
